#!/usr/bin/env python3
"""
GitCode界面模块

提供GitCode平台相关的用户界面组件和交互逻辑。
包含仓库获取、提交分析、侧边栏配置等功能。
"""

import os
import random
from typing import List, Dict, Tuple

import pandas as pd
import streamlit as st
from loguru import logger

# 导入GitCode相关类
from platforms.gitcode import GitCodeInterface as GitCodeAPI


class GitCodeInterface:
    """GitCode界面管理类"""

    def __init__(self):
        self.api = GitCodeAPI()

    @staticmethod
    def get_random_gitcode_token() -> str:
        """从环境变量中获取随机GitCode访问令牌"""
        token_str = os.getenv('GITCODE_ACCESS_TOKEN', '')
        if not token_str:
            return ''
        tokens = [token.strip() for token in token_str.split(',') if token.strip()]
        if not tokens:
            return ''
        return random.choice(tokens)

    def render_sidebar_config(self) -> Tuple[str, str]:
        """渲染GitCode侧边栏配置"""
        st.sidebar.subheader("🔧 GitCode 配置")

        # 获取环境变量中的token
        env_token = self.get_random_gitcode_token()
        if env_token:
            st.sidebar.success(f"✅ 已从环境变量随机选择GitCode Token（前8位: {env_token[:8]}...)")
        else:
            st.sidebar.info("ℹ️ 未检测到GitCode环境变量，请手动输入Access Token")

        # Access Token输入
        access_token = st.sidebar.text_input(
            "GitCode Access Token",
            value=env_token,
            type="password",
            help="GitCode API访问令牌",
            key="gitcode_access_token"
        )

        # 组织名称输入
        org_name = st.sidebar.text_input(
            "组织名称",
            value="dlut-water",
            help="要分析的GitCode组织名称",
            key="gitcode_org_name"
        )

        return access_token, org_name

    def fetch_repositories(self, access_token: str, org_name: str) -> pd.DataFrame:
        """获取GitCode仓库列表"""
        try:
            with st.spinner(f"正在获取GitCode组织 '{org_name}' 的仓库列表..."):
                df = self.api.fetch_repositories(access_token, org_name)
            return df
        except Exception as e:
            st.error(f"获取GitCode仓库列表失败: {str(e)}")
            logger.error(f"获取GitCode仓库列表失败: {e}")
            return pd.DataFrame()

    def fetch_commits(self, access_token: str, owner: str, repo: str, since_date: str = None) -> pd.DataFrame:
        """获取GitCode提交记录"""
        try:
            with st.spinner(f"正在获取GitCode仓库 '{owner}/{repo}' 的提交记录..."):
                df = self.api.fetch_commits(access_token, owner, repo, since_date)
            return df
        except Exception as e:
            st.error(f"获取GitCode提交记录失败: {str(e)}")
            logger.error(f"获取GitCode提交记录失败: {e}")
            return pd.DataFrame()

    def fetch_overall_analysis(self, access_token: str, org_name: str, repos_df: pd.DataFrame,
                               since_date: str) -> List[pd.DataFrame]:
        """获取GitCode所有仓库的整体分析数据"""
        try:
            overall_data = []

            progress_bar = st.progress(0)
            status_text = st.empty()

            total_repos = len(repos_df)

            for idx, repo in repos_df.iterrows():
                repo_name = repo['name']
                status_text.text(f"正在分析GitCode仓库: {repo_name} ({idx + 1}/{total_repos})")

                try:
                    # 获取该仓库的提交数据
                    df = self.api.fetch_commits(access_token, org_name, repo_name, since_date)

                    if not df.empty:
                        # 添加仓库信息
                        df['repo_name'] = repo_name
                        overall_data.append(df)

                except Exception as e:
                    logger.error(f"分析GitCode仓库 {repo_name} 失败: {e}")
                    continue

                # 更新进度
                progress_bar.progress((idx + 1) / total_repos)

            progress_bar.empty()
            status_text.empty()

            return overall_data

        except Exception as e:
            st.error(f"GitCode整体分析失败: {str(e)}")
            logger.error(f"GitCode整体分析失败: {e}")
            return []

    def fetch_student_analysis(self, access_token: str, org_name: str, repos_df: pd.DataFrame,
                               since_date: str) -> List[Dict]:
        """获取GitCode提交者级别的详细分析数据"""
        try:
            # 获取仓库信息
            repo_names = repos_df['name'].tolist()
            st.info(f"📊 开始分析 {len(repo_names)} 个GitCode仓库的提交者统计数据...")

            st.info("⏱️ 由于API频率限制，每个仓库的每个分支需要约2秒的处理时间，请耐心等待...")

            # 创建进度条
            progress_bar = st.progress(0)
            status_text = st.empty()

            # 定义进度回调函数
            def update_progress(current, total, repo_name, branches_count=0):
                progress = int((current / total) * 100)
                progress_bar.progress(progress)
                if branches_count > 0:
                    status_text.text(f"正在处理仓库 {current}/{total}: {repo_name} ({branches_count} 个分支)")
                else:
                    status_text.text(f"正在处理仓库 {current}/{total}: {repo_name}")

            # 获取提交者统计数据
            student_stats = self.api.fetch_student_analysis(
                access_token, org_name, repos_df, since_date, progress_callback=update_progress
            )

            # 完成进度条
            progress_bar.progress(100)
            status_text.success(f"✅ 成功分析了 {len(repo_names)} 个GitCode仓库的数据")

            return student_stats

        except Exception as e:
            st.error(f"GitCode提交者分析失败: {str(e)}")
            logger.error(f"GitCode提交者分析失败: {e}")
            return []

    def display_platform_info(self):
        """显示GitCode平台信息"""
        st.markdown(
            '<div class="gitcode-legacy">'
            '<h4>🔵 GitCode 平台</h4>'
            '<p>传统的GitCode API分析模式，适用于组织级别的代码仓库分析。</p>'
            '</div>',
            unsafe_allow_html=True
        )
